﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using System.Collections.Generic;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxCooperativeController : Controller
    {
        YqdContext ctx;

        public WxCooperativeController(YqdContext ctx)
        {
            this.ctx = ctx;
        }

       [User]
        public ActionResult GetList()
        {
            var TaskID = Form.GetLong("TaskID");
            var CooperativeID = Form.GetInt("CooperativeID");
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var r = ctx.Yqd_Cooperative.Where(it => it.TaskID == TaskID);
            if (CooperativeID > 0) r = r.Where(it => it.CooperativeID == CooperativeID);
            r = r.OrderByDescending(it => it.Instime);
            var totalcount = r.Count();
            if (pagesize > 0)
            {
                r = r.Skip((page - 1) * pagesize).Take(pagesize);
            }
            var l = WxUser.LogonInfo;
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == TaskID);
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            return this.ToJson(new
            {
                success = true,
                totalcount,
                task.TaskName,
                data = r.ToList().Select(it => new
                {
                    it.CooperativeID,
                    Content = it.Item ?? "",
                    RespondTime = it.RespondTime.ToString("yyyy-MM-dd"),
                    CooperativeResult = Enum.GetName(typeof(协同结果), it.CooperativeResult),
                    it.ReplySituation,
                    it.WorkProgress,
                    IsReply = it.CooperativeUnit == l.UnitCode && (it.CooperativeResult == 协同结果.未反馈 || it.CooperativeResult == 协同结果.未办理落实),
                    CompletionTime = it.CompletionTime != null ? it.CompletionTime.ToString("yyyy-MM-dd") : "",
                    Reason = it.Reason ?? "",
                    Dept = dept.FirstOrDefault(d => d.UnitCode == it.UnitCode)?.Name,
                    CooperativeUnit = dept.FirstOrDefault(d => d.UnitCode == it.CooperativeUnit)?.Name,
                    Instime = it.Instime.ToString("yyyy-MM-dd")
                })
            });
        }

        [User]
        public ActionResult GetMyCooperativeList()
        {
            var flag = Form.GetInt("flag", 1);
            if (flag > 3) flag = 3;
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var l = WxUser.LogonInfo;
            var nt = DateTime.Now.Date;
            var r = ctx.Yqd_Cooperative.AsQueryable();
            switch (flag)
            {
                case 0:
                case 1:
                    r = r.Where(it => it.UnitCode == l.UnitCode);
                    break;
                case 2:
                    r = r.Where(it => it.CooperativeUnit == l.UnitCode && it.CooperativeResult != 协同结果.未反馈);
                    break;
                case 3:
                    r = r.Where(it => it.UnitCode == l.UnitCode && (it.CooperativeResult != 协同结果.未反馈 || (it.CooperativeResult == 协同结果.未反馈 && it.RespondTime.AddDays(3) < nt)));
                    break;
            }
            var tIDs = r.Select(it => it.TaskID).ToArray();
            var tasks = ctx.Yqd_Task.Where(it => tIDs.Contains(it.TaskID)).Select(it => new { it.TaskID, it.TaskName, it.LeaderUnitName, it.CreateTime, it.FAreaCode, it.TaskStatus }).ToList();
            r = r.OrderByDescending(it => it.Instime);
            var totalcount = r.Count();
            if (pagesize > 0)
            {
                r = r.Skip((page - 1) * pagesize).Take(pagesize);
            }
            else
            {
                r = r.Take(2);
            }
            dynamic t = null;
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data = r.ToList().Select(it => new
                {
                    TaskID = it.TaskID.ToString(),
                    it.CooperativeID,
                    (t = tasks.FirstOrDefault(n => n.TaskID == it.TaskID))?.TaskName,
                    t.LeaderUnitName,
                    TaskStatus = Enum.GetName(typeof(任务状态), t.TaskStatus),
                    Status = Enum.GetName(typeof(协同结果), it.CooperativeResult),
                    CreateTime = t.CreateTime.ToString("yyyy.MM.dd"),
                    Content = it.Item,
                    AssignLimit = it.RespondTime.ToString("yyyy.MM.dd")
                })
            });
        }

        /// <summary>
        /// 添加协同事项
        /// </summary>
        /// <returns></returns>
       [User]
        public IActionResult Add()
        {
            var TaskID = Form.GetLong("TaskID");
            var datas = Form.GetString("datas").ToJArray();
            var lst = new List<Yqd_Cooperative>();
            foreach (var info in datas)
            {
                lst.Add(new Yqd_Cooperative
                {
                    TaskID = TaskID,
                    Item = info["Item"].ToString(),
                    CooperativeUnit = info["CooperativeUnit"].ToString(),
                    RespondTime = DateTime.Parse(info["RespondTime"].ToString()),
                    CooperativeResult = 0,
                    Instime = DateTime.Now,
                    EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                    UnitCode = WxUser.LogonInfo.UnitCode
                });
            }
            ctx.Yqd_Cooperative.AddRange(lst);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                foreach (var m in lst)
                {
                    TaskLogService.AddLog(TaskID, "向" + ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == m.CooperativeUnit)?.Name + "发起了协同");
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        /// <summary>
        /// 反馈协同
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
       [User]
        public IActionResult Feedback()
        {
            var TaskID = Form.GetLong("TaskID");
            var CooperativeID = Form.GetInt("CooperativeID");
            var CooperativeResult = Form.GetInt("CooperativeResult");
            var ReplySituation = Form.GetString("ReplySituation");
            var WorkProgress = Form.GetString("WorkProgress");
            var CompletionTime = Form.GetString("CompletionTime");
            var Reason = Form.GetString("Reason");
            var sql = "update Yqd_Cooperative set CooperativeResult={1},FeedbackTime=getdate()";
            switch ((协同结果)CooperativeResult)
            {
                case 协同结果.已办理落实:
                    sql += ",ReplySituation={2}";
                    break;
                case 协同结果.未办理落实:
                    sql += ",WorkProgress={3},FeedbackTime={4}";
                    break;
                case 协同结果.无法办理:
                    sql += ",Reason={5}";
                    break;
            }
            sql += " where CooperativeID={0};";
            var ret = ctx.Database.ExecuteSql(sql, CooperativeID, CooperativeResult, ReplySituation, WorkProgress, CompletionTime, Reason);
            if (ret > 0)
            {
                TaskLogService.AddLog(TaskID, "反馈了协同");
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var CooperativeID = Form.GetInt("CooperativeID");
            var ret = ctx.Database.ExecuteSql("delete from Yqd_Cooperative where CooperativeID={0}", CooperativeID);
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
